import cv2 as cv
filename = r'E:\images\rice.jpg'
img = cv.imread(filename)

gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
_, bw = cv.threshold(gray, 0, 0xff, cv.THRESH_OTSU)
elements = cv.getStructuringElement(cv.MORPH_CROSS, (3, 3))
bw = cv.morphologyEx(bw, cv.MORPH_OPEN, elements)

#seg = copy.deepcopy(bw)
bin, cnts, hier = cv.findContours(bw, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
count = 0

for i in range(len(cnts), 0, -1):
    c = cnts[i - 1]
    area = cv.contourArea(c)
    length = cv.arcLength(c, True)

    (mean, stddv) = cv.meanStdDev(c)
    if area < 10:
        continue
    count = count + 1
    print("blob", i, " 面积: ", area, "长度:", length, "均值：", mean, "方差：", stddv)

    x, y, w, h = cv.boundingRect(c)
    cv.rectangle(img, (x, y), (x+w, y+h), (0, 0, 0xff), 1)
    cv.putText(img, str(count), (x, y), cv.FONT_HERSHEY_PLAIN, 0.5, (0, 0xff, 0))

print(u"米粒数量：", count)
cv.imshow(u"原图：", img)
cv.imshow(u"阈值化图：", bw)

cv.waitKey()
cv.destroyAllWindows()


